package idv.arthur.JCraft;

import java.io.IOException;
import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class Script2AP {
	public static void main(String[] arg) throws IOException {
		
		InputStream in = null;
		Channel channel = null;
		Session session = null;
		try {
			final JSch jsch = new JSch();
			
			java.util.Properties config = new java.util.Properties(); 
			config.put("StrictHostKeyChecking", "no");
			
			session = jsch.getSession("root", "10.144.97.99", 22);
			session.setConfig(config);
			session.setPassword("arthur7382");
			session.connect();
			
			channel = session.openChannel("exec");
			((ChannelExec) channel).setCommand("service httpd stop");

			channel.setInputStream(null);

			((ChannelExec) channel).setErrStream(System.err);
//Stopping httpd: [  OK  ]
			in = channel.getInputStream();

			channel.connect();

			byte[] tmp = new byte[1024];
			while (true) {
				while (in.available() > 0) {
					int i = in.read(tmp, 0, 1024);
					if (i < 0)
						break;
					System.out.print(new String(tmp, 0, i));
				}
				if (channel.isClosed()) {
					System.out.println("結束了");
					break;
				}
				try {
					Thread.sleep(1000);
				} catch (Exception ee) { ee.printStackTrace(); }
			}
			channel.disconnect();
			session.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if ( in != null) { in.close(); }
			if ( channel.isConnected() ) { channel.disconnect(); }
			if ( session.isConnected() ) { session.disconnect(); }
		}
	}
}
